package no.ntnu.item.ttm4115.termproject.teacheragent.gui;

import java.awt.event.ActionEvent;
import java.util.Vector;

import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;

import com.thoughtworks.xstream.XStream;

import no.ntnu.item.ttm4115.termproject.DeleteGroupFromGUI;
import no.ntnu.item.ttm4115.termproject.DeleteTreasureFromGUI;
import no.ntnu.item.ttm4115.termproject.UpdateGroupFromGUI;
import no.ntnu.item.ttm4115.termproject.UpdatePlayerSettingsFromGUI;
import no.ntnu.item.ttm4115.termproject.UpdateTreasureInXML;
import no.ntnu.item.ttm4115.termproject.extrasagent.Group;
import no.ntnu.item.ttm4115.termproject.extrasagent.Player;
import no.ntnu.item.ttm4115.termproject.extrasagent.SessionOption;
import no.ntnu.item.ttm4115.termproject.extrasagent.SessionQuestion;
import no.ntnu.item.ttm4115.termproject.extrasagent.Treasures;
import no.tellu.common.actorframe.ActorSM;
import no.tellu.common.javaframe.ActorAddress;

/*
 * ModifyGroup.java
 *
 * Created on 6. august 2008, 11:39
 */



/**
 *
 * @author  bruker
 */
public class ModifyGroup extends javax.swing.JPanel {
	private TeacherGUI gui;
	private ActorSM asm;
	private Group selectedGroup;
	private String oldGroupName;
    /** Creates new form ModifyGroup */
    public ModifyGroup(TeacherGUI gui,ActorSM asm) {
        gui.setStartPanel(this);
        this.gui = gui;
        this.asm = asm;
        initComponents();
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this.gui.getContentPane());
        this.gui.getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(this, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(this, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
    	
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jSeparator1 = new javax.swing.JSeparator();
        headLabel = new javax.swing.JLabel();
        availableGroupsComboBox = new javax.swing.JComboBox();
        availableGroupsModel = new DefaultComboBoxModel();
        selectGroupButton = new javax.swing.JButton();
        groupNameLabel = new javax.swing.JLabel();
        groupNameTextField = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        groupPlayersList = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        availablePlayersList = new javax.swing.JList();
        groupPlayersLabel = new javax.swing.JLabel();
        availablePlayersLabel = new javax.swing.JLabel();
        removePlayersButton = new javax.swing.JButton();
        addPlayersGroup = new javax.swing.JButton();
        saveGroupButton = new javax.swing.JButton();
        deleteGroupButton = new javax.swing.JButton();
        availablePlayersListModel = new javax.swing.DefaultListModel();
        groupPlayersListModel = new javax.swing.DefaultListModel();

        headLabel.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        headLabel.setText("Modify Group");

        
        fillGroupDropDown(availableGroupsModel);
        availableGroupsComboBox.setModel(availableGroupsModel);
        
        selectGroupButton.setText("Select");
        selectGroupButton.addActionListener(new java.awt.event.ActionListener() {
        	public void actionPerformed(java.awt.event.ActionEvent evt){
        		selectGroupButtonActionPerformed(evt);
        	}
        });
        groupNameLabel.setText("Group Name");
        
        
        groupPlayersList.setModel(groupPlayersListModel);
        jScrollPane1.setViewportView(groupPlayersList);

        
        availablePlayersList.setModel(availablePlayersListModel);
        jScrollPane2.setViewportView(availablePlayersList);

        groupPlayersLabel.setText("Group Players");

        availablePlayersLabel.setText("Available Players");
        
        removePlayersButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("001_25.png"))); // NOI18N
        removePlayersButton.addActionListener(new java.awt.event.ActionListener() {
        	public void actionPerformed(java.awt.event.ActionEvent evt){
        		removePlayersButtonActionPerformed(evt);
        	}
        });
        addPlayersGroup.setIcon(new javax.swing.ImageIcon(getClass().getResource("001_27.png"))); // NOI18N
        addPlayersGroup.addActionListener(new java.awt.event.ActionListener() {
        	public void actionPerformed(java.awt.event.ActionEvent evt){
        		addPlayersButtonActionPerformed(evt);
        	}
        });
        
        saveGroupButton.setText("Save Group");
        saveGroupButton.addActionListener(new java.awt.event.ActionListener() {
        	public void actionPerformed(java.awt.event.ActionEvent evt){
        		saveGroupButtonActionPerformed(evt);
        	}
        });
        saveGroupButton.setEnabled(false);
        deleteGroupButton.setText("Delete Group");
        deleteGroupButton.addActionListener(new java.awt.event.ActionListener() {
        	public void actionPerformed(java.awt.event.ActionEvent evt){
        		deleteGroupButtonActionPerformed(evt);
        	}
        });
        deleteGroupButton.setEnabled(false);
        
        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 550, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(headLabel)
                .addGap(18, 18, 18)
                .addComponent(availableGroupsComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 105, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(selectGroupButton)
                .addContainerGap(255, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(groupNameLabel)
                .addGap(18, 18, 18)
                .addComponent(groupNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(373, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(groupPlayersLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(addPlayersGroup, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(removePlayersButton, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(8, 8, 8)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(availablePlayersLabel)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(286, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(saveGroupButton)
                .addGap(18, 18, 18)
                .addComponent(deleteGroupButton)
                .addContainerGap(338, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(17, 17, 17)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(headLabel)
                    .addComponent(availableGroupsComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(selectGroupButton))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(groupNameLabel)
                    .addComponent(groupNameTextField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(groupPlayersLabel)
                            .addComponent(availablePlayersLabel))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jScrollPane2)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(62, 62, 62)
                        .addComponent(addPlayersGroup)
                        .addGap(18, 18, 18)
                        .addComponent(removePlayersButton)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 58, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(saveGroupButton)
                    .addComponent(deleteGroupButton))
                .addGap(36, 36, 36))
        );
    }// </editor-fold>


    private void fillGroupDropDown(DefaultComboBoxModel model) {
    	for (int i = 0; i < gui.getGroups().size(); i++) {
			model.addElement(gui.getGroups().elementAt(i).getGroupName());
		}
		
	}

    private void deleteGroupButtonActionPerformed(ActionEvent evt) {
    	int remove = -9;
    	for (int i = 0; i < gui.getGroups().size(); i++) {
			if(gui.getGroups().elementAt(i).getGroupName().equals(selectedGroup.getGroupName())){
				gui.getGroups().remove(i);
				remove = i;
			}
		}
    	XStream xstream = new XStream();
		xstream.setClassLoader(new Group().getClass().getClassLoader());
		xstream.setClassLoader(new Player().getClass().getClassLoader());
		xstream.alias("group", Group.class);
		xstream.alias("player",Player.class);
		xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);
		
		String group = xstream.toXML(selectedGroup);
		
		asm.sendMessage(new DeleteGroupFromGUI(group),new ActorAddress("/classManager","ClassManager"));
		if(remove != -9){
			availableGroupsModel.removeElementAt(remove);
		}
		resetScheme();
	}

	private void saveGroupButtonActionPerformed(ActionEvent evt) {
		selectedGroup.setGroupName(groupNameTextField.getText());
		
		Vector<String> groupPlayersVector = new Vector<String>();
		for(int i=0; i<groupPlayersListModel.getSize();i++){
			groupPlayersVector.add((String) groupPlayersListModel.getElementAt(i));
		}
		selectedGroup.setPlayers(mergeStringAndPlayer(groupPlayersVector));
		
		
		XStream xstream = new XStream();
		xstream.setClassLoader(new Group().getClass().getClassLoader());
		xstream.setClassLoader(new Player().getClass().getClassLoader());
		xstream.alias("group", Group.class);
		xstream.alias("player",Player.class);
		xstream.setMode(XStream.XPATH_ABSOLUTE_REFERENCES);
		
		String group = xstream.toXML(selectedGroup);
		asm.sendMessage(new UpdateGroupFromGUI(group,oldGroupName),new ActorAddress("/classManager","ClassManager"));
		availableGroupsComboBox.repaint();
	}
	private Vector<Player> mergeStringAndPlayer(Vector<String> stringVector){
		Vector<Player> finalPlayerVector = new Vector<Player>();
		for (int i = 0; i < stringVector.size(); i++) {
			for (int j = 0; j < gui.getPlayers().size(); j++) {
				if(stringVector.elementAt(i).toString().equals(gui.getPlayers().elementAt(j).getUserName().toString())){
					finalPlayerVector.add(gui.getPlayers().elementAt(j));
				}
			}
		}	
		return finalPlayerVector; 
	} 

	private void addPlayersButtonActionPerformed(ActionEvent evt) {
		Object[] playersToBeAdded =  availablePlayersList.getSelectedValues();
    	System.out.println(playersToBeAdded[0]);
		fillAddedPlayersList(playersToBeAdded);
			
	}
	private void fillAddedPlayersList(Object[] players){
    	if(players != null){
			for(int i=0; i<players.length;i++){
				if(checkAddedPlayersList((String) players[i])){
					groupPlayersListModel.addElement((players[i]));
				}
			}
		}
    	groupPlayersList.repaint();
    }
	 private boolean checkAddedPlayersList(String player){
			boolean booleanValue = true;
			for(int i=0; i<groupPlayersListModel.getSize();i++){
				if(groupPlayersListModel.getElementAt(i).equals(player)){
					booleanValue = false;
					break;
				}
			}
			return booleanValue;
		}

	private void removePlayersButtonActionPerformed(ActionEvent evt) {
		Object[] playersToBeRemoved =  groupPlayersList.getSelectedValues();
		removePlayersFromAddedList(playersToBeRemoved);
	}
	
	private void removePlayersFromAddedList(Object[] players){
    	if(players != null){
    		for (int i = 0; i < players.length; i++) {
				for (int j = 0; j < groupPlayersListModel.size(); j++) {
					if(players[i].equals(groupPlayersListModel.elementAt(j))){
						groupPlayersListModel.remove(j);
					}
				}
			}
    	}
    }

	private void selectGroupButtonActionPerformed(ActionEvent evt) {
		resetScheme();
		saveGroupButton.setEnabled(true);
		deleteGroupButton.setEnabled(true);
		fillAvailablePlayers(availablePlayersListModel);
		String groupName = (String) availableGroupsComboBox.getModel().getSelectedItem();
		Group loadedGroup = loadGroup(groupName);
		
		if(loadedGroup != null){
			updateGroupValues(loadedGroup);
			selectedGroup = loadedGroup;
			oldGroupName = selectedGroup.getGroupName();
			
		}else{
			System.out.println("feil ");
		}
		
		
	}
	   private Group loadGroup(String name){
	    	Group group = new Group();
	    	for (int i = 0; i < gui.getGroups().size(); i++) {
				if(gui.getGroups().elementAt(i).getGroupName().equals(name)){
					group.setChat(gui.getGroups().elementAt(i).isChat());
					group.setDiscussion(gui.getGroups().elementAt(i).isDiscussion());
					group.setIm(gui.getGroups().elementAt(i).isIm());
					group.setGroupName(name);
					group.setLeader(gui.getGroups().elementAt(i).getLeader());
					group.setPlayers(gui.getGroups().elementAt(i).getPlayers());
					break;
				}
			}
	    	return group;
	    }
	private void updateGroupValues(Group group){
    	groupNameTextField.setText(group.getGroupName());
    	
    	groupPlayersListModel.removeAllElements();
    	for (int i = 0; i < group.getPlayers().size(); i++) {
    		groupPlayersListModel.addElement(group.getPlayers().elementAt(i).getUserName());
    	}
    	groupPlayersList.repaint();
    }
	private void resetScheme(){
		groupNameTextField.setText("");
		groupPlayersListModel.removeAllElements();
	}
	
	private void fillAvailablePlayers(DefaultListModel model) {
		for (int i = 0; i < gui.getPlayers().size(); i++) {
			model.addElement(gui.getPlayers().elementAt(i).getUserName());
		}
		
	}

	private void fillGroupPlayers(DefaultListModel model) {
		for (int i = 0; i < selectedGroup.getPlayers().size(); i++) {
			model.addElement(selectedGroup.getPlayers().elementAt(i).getUserName());
		}
		
	}


	// Variables declaration - do not modify
    private javax.swing.JButton addPlayersGroup;
    private javax.swing.JComboBox availableGroupsComboBox;
    private javax.swing.JLabel availablePlayersLabel;
    private javax.swing.JButton deleteGroupButton;
    private javax.swing.JLabel groupNameLabel;
    private javax.swing.JTextField groupNameTextField;
    private javax.swing.JLabel groupPlayersLabel;
    private javax.swing.JLabel headLabel;
    private javax.swing.JList groupPlayersList;
    private javax.swing.JList availablePlayersList;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JButton removePlayersButton;
    private javax.swing.JButton saveGroupButton;
    private javax.swing.JButton selectGroupButton;
    private javax.swing.DefaultListModel availablePlayersListModel;
    private javax.swing.DefaultListModel groupPlayersListModel;
    private javax.swing.DefaultComboBoxModel availableGroupsModel;
    // End of variables declaration

}
